(** 
    XMLParser.ml

    Bozman Çagdas <bozman.cagdas@gmail.com> - 2011
    Razakamiadana Tefin <tefy.razaka@gmail.com>   - 2011
*)
open Utils 
open Sets

type xml = Xml.xml

let wikitext = "wikitext"

let check s = 
  Str.global_replace (Str.regexp "\\") "\\\\\\\\" s

let parse_string s = 
  try 
    Xml.parse_string s
  with
    | Xml.Error err -> failwith (Xml.error err)

let attribs_list s =
  let s = check s in
  let xml = parse_string s in
  let rec aux accu = function
    | [] -> accu
    | node :: nodes ->
      let accu, l =
	match node with
	  | Xml.Element (_, attrs, next) -> 
	    attrs :: accu, nodes @ next
	  | Xml.PCData _ -> accu, nodes
      in
      aux accu l
  in
  aux [] [xml]

let wiki_text = 
  let init = "" in
  fun s ->
    let s = check s in
    let xml = parse_string s in  
    let rec aux res = function
      | [] -> res
      | node :: nodes ->
	let res, l =
	  match node with
  	    | Xml.Element (tag, _, next) ->
  	      if tag = wikitext then
  		Xml.to_string_fmt node, nodes
  	      else
  		res, nodes @ next
	    | _ -> res, nodes
	in
	aux res l
    in
    aux init [ xml ]
